<template>
    <view>
        <!-- pages/shopmanager/addqualityservice/index.wxml -->
        <view>
            <view class="box">
                <view class="centers" @tap="showStationBtn">
                    <view class="text1">项目名称</view>
                    <view class="centers-1">
                        <input class="weui-input" @input="getdata1" maxlength="15" type="text" :value="name1" placeholder="请输入项目名称" />
                    </view>
                </view>
                <view class="divLine"></view>
                <view class="centers" @tap="onEnvironment">
                    <view class="text1">项目现价格</view>
                    <view class="centers-1">
                        <input class="weui-input" maxlength="5" @input="getdata2" :value="name2" type="number" placeholder="请输入项目现价" />
                    </view>
                </view>
                <view class="divLine"></view>
                <view class="centers" @tap="onServices">
                    <view class="text1">项目原价格</view>
                    <view class="centers-1">
                        <input @input="getdata3" maxlength="5" :value="name3" class="weui-input" type="number" placeholder="请输入项目原价（可不填）" />
                    </view>
                </view>
            </view>
            <view class="box">
                <view class="centers" @tap="onServices">
                    <view class="text1">服务美发师</view>
                    <view class="centers_1" @tap="showType">
                        <text class="text2">{{ newtype.nickname ? newtype.nickname : '选择美发师' }}</text>
                        <image class="icon-32" :src="imgUrl + 'right.png'"></image>
                    </view>
                </view>
            </view>
            <view class="box">
                <view class="centers" @tap="showTime">
                    <view class="text1">服务时长</view>
                    <view class="centers_1">
                        <text class="text2">{{ hour }}小时{{ minute }}分钟</text>
                        <image class="icon-32" :src="imgUrl + 'right.png'"></image>
                    </view>
                </view>
            </view>
            <view class="box">
                <view class="centers" @tap="onServices">
                    <view class="text1">选择项目主图</view>
                    <view class="">
                        <van-uploader
                            max-count="1"
                            :file-list="fileList"
                            :deletable="true"
                            preview-size="200rpx"
                            @after-read="afterRead"
                            upload-icon="https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/images/take.png"
                            @delete="ondelete"
                            upload-text="添加照片"
                        ></van-uploader>
                    </view>
                </view>
            </view>
        </view>
        <van-popup :show="showtype" round position="bottom" custom-style="height: 250px" @close="onCloseType" close-icon="cross" closeable>
            <view class="pbox1 mt-100">
                <van-picker
                    show-toolbar
                    title="标题"
                    :columns="datalist"
                    @cancel="onCancel"
                    @change="onChangeType"
                    :show-toolbar="false"
                    custom-class="pbox"
                    visible-item-count="3"
                    value-key="nickname"
                />
            </view>

            <view class="btn1" @tap="onType">确定</view>
        </van-popup>
        <van-popup :show="showtime" round position="bottom" custom-style="height: 250px" @close="onCloseTime" close-icon="cross" closeable>
            <view class="pbox1 mt-100">
                <van-picker show-toolbar :show-toolbar="false" @cancel="onCloseType" custom-class="pbox" :columns="columns" @change="onChangetime" visible-item-count="3" />
            </view>
            <view class="btn1" @tap="onTime">确定</view>
        </van-popup>

        <view class="savebtn" @tap.stop.prevent="onSave">上架</view>
    </view>
</template>

<script>
// pages/shopmanager/addqualityservice/index.js
const app = getApp(); // 引入app

import _request from '../../../utils/request.js';
const list = {
    '0小时': ['0分钟', '30分钟'],
    '1小时': ['0分钟', '30分钟'],
    '2小时': ['0分钟', '30分钟'],
    '3小时': ['0分钟', '30分钟'],
    '4小时': ['0分钟', '30分钟'],
    '5小时': ['0分钟', '30分钟']
};
export default {
    data() {
        return {
            requesttype: 0,
            //区分是修改还是新增
            imgUrl: app.globalData.imgUrl,
            //全局img路径
            fileList: [],
            datalist: [],
            showtype: false,
            showtime: false,
            name1: '',
            // 服务名
            name2: '',
            // 现价
            name3: '',
            // 原价
            newtype: {
                nickname: false
            },
            oldtype: '',
            hour: '0',
            minute: '0',
            oldhour: '0',
            oldmint: '0',
            columns: [
                {
                    values: Object.keys(list),
                    className: 'column1'
                },
                {
                    values: list['0小时'],
                    className: 'column2',
                    defaultIndex: 0
                }
            ],
            id: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        let data = null;

        if (options.data) {
            data = JSON.parse(options.data);
        } // 获取门店所有理发师列表

        _request
            .get('/store/getStoreAllStylistList', {
                storeId: uni.getStorageSync('storeId')
            })
            .then((res) => {
                // console.log(res)
                if (res.data.code === 200) {
                    this.setData({
                        datalist:
                            res.data.data.map((item) => {
                                item.nickname = item.nickname + (item.nexus == 0 ? '（网约）' : '（店内）');
                                return item;
                            }) || []
                    });

                    if (data) {
                        let str = this.datalist.filter((item) => {
                            if (item.stylistId == data.stylistId) {
                                return item;
                            }
                        })[0];
                        this.setData({
                            hour: data.hour,
                            minute: data.minute,
                            name3: data.oldPrice,
                            name1: data.serviceName,
                            name2: data.newPrice,
                            fileList: [
                                {
                                    url: data.path,
                                    deletable: true,
                                    isImage: true
                                }
                            ],
                            requesttype: 1,
                            newtype: str,
                            id: data.id
                        });
                    }
                }
            });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        //确定时间10分钟>时间<5小时
        onTime() {
            const { oldhour, oldmint } = this;

            if (oldhour == 5 && oldmint != 0) {
                uni.showToast({
                    title: '时间最大区间为五小时',
                    icon: 'none',
                    duration: 2000
                });
            } else {
                this.setData({
                    hour: oldhour,
                    minute: oldmint,
                    showtime: false
                });
            }
        },

        // 获取选择时间
        onChangetime(event) {
            const { picker, value, index } = event.detail;
            this.setData({
                oldhour: value[0].split('小时')[0],
                oldmint: value[1].split('分钟')[0]
            });
        },

        // 显示时间弹窗
        showTime() {
            this.setData({
                showtime: true
            });
        },

        // 关闭窗口
        onCloseTime() {
            this.setData({
                showtime: false
            });
        },

        // 显示类型弹窗
        showType() {
            this.setData({
                showtype: true,
                oldtype: this.oldtype ? this.oldtype : this.datalist[0]
            });
        },

        // 获取选择类型
        onChangeType(event) {
            const { value } = event.detail;
            this.setData({
                oldtype: value
            });
        },

        // 确定
        onType() {
            this.setData({
                showtype: false,
                newtype: this.oldtype
            });
        },

        // 关闭窗口
        onCloseType() {
            this.setData({
                showtype: false
            });
        },

        // 获取输入值
        getdata1(e) {
            const { value } = e.detail;
            var reg = /[^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n]/g;
            this.setData({
                name1: value?.replace(reg, '') //清除表情
            });
        },

        getdata2(e) {
            const { value } = e.detail;

            if (value > 99999) {
                this.setData({
                    name2: 99999
                });
            } else {
                this.setData({
                    name2: value
                });
            }
        },

        getdata3(e) {
            const { value } = e.detail;

            if (value > 99999) {
                this.setData({
                    name3: 99999
                });
            } else {
                this.setData({
                    name3: value
                });
            }
        },

        // 上传图片
        afterRead(event) {
            let _this = this;

            const { file } = event.detail;
            uni.showLoading({
                title: '上传中',
                mask: true
            });
            uni.uploadFile({
                url: app.globalData.baseurl + '/store-api/file/batchUpload',
                filePath: file.url,
                name: 'files',
                header: {
                    token: uni.getStorageSync('token')
                },
                formData: {
                    files: 'file'
                },

                success(res) {
                    const data = JSON.parse(res.data).data[0];
                    uni.hideLoading({
                        success: (res) => {
                            _this.setData({
                                fileList: [..._this.fileList, { ...file, url: data, deletable: true, isImage: true }]
                            });
                        }
                    });
                },

                fail(error) {
                    console.log(error);
                },

                complete(res) {
                    console.log(res);
                }
            });
        },

        // 删除图片
        ondelete(e) {
            const { file } = e.detail;
            let list = this.fileList.filter((item) => {
                return item.size != file.size;
            });
            this.setData({
                fileList: list
            });
        },

        onSave() {
            if (!this.fileList.length) {
                uni.showToast({
                    title: '请添加照片',
                    icon: 'none',
                    duration: 2000
                });
                return;
            } else if (!this.newtype) {
                uni.showToast({
                    title: '请选择美发师',
                    icon: 'none',
                    duration: 2000
                });
                return;
            } else if (this.hour == 0 && this.minute == 0) {
                uni.showToast({
                    title: '请选择服务时长',
                    icon: 'none',
                    duration: 2000
                });
                return;
            } else if (!this.name2 || this.name2 == 0) {
                uni.showToast({
                    title: '请填写现价且不能为0',
                    icon: 'none',
                    duration: 2000
                });
                return;
            }

            const { fileList, hour, minute, name1, name2, name3, newtype, requesttype, id } = this;
            let list = fileList.map((item) => {
                return item.url;
            });
            let url = requesttype ? '/store/updateQualityService' : '/store/insertQualityService';
            let obj;

            if (requesttype) {
                obj = {
                    serviceName: name1,
                    path: list[0],
                    newPrice: name2,
                    oldPrice: name3,
                    storeId: uni.getStorageSync('storeId'),
                    stylistId: newtype.stylistId,
                    hour,
                    minute: minute,
                    id
                };
            } else {
                obj = {
                    serviceName: name1,
                    path: list[0],
                    newPrice: name2,
                    oldPrice: name3,
                    storeId: uni.getStorageSync('storeId'),
                    stylistId: newtype.stylistId,
                    hour,
                    minute: minute
                };
            }

            _request
                .postObj(url, { ...obj })
                .then((res) => {
                    if (res.data.code === 200) {
                        uni.showToast({
                            title: '添加成功',
                            icon: 'none',
                            duration: 2000
                        });
                        this.setData({
                            fileList: [],
                            datalist: [],
                            showtype: false,
                            showtime: false,
                            name1: '',
                            name2: '',
                            name3: '',
                            newtype: '',
                            oldtype: '',
                            hour: '0',
                            minute: '0',
                            oldhour: '0',
                            oldmint: '0'
                        });
                        uni.navigateBack({
                            delta: 1
                        });
                    }
                })
                .catch((error) => {
                    console.log(error, 'error');
                });
        },

        showStationBtn() {
            console.log('占位：函数 showStationBtn 未声明');
        },

        onEnvironment() {
            console.log('占位：函数 onEnvironment 未声明');
        },

        onServices() {
            console.log('占位：函数 onServices 未声明');
        },

        onCancel() {
            console.log('占位：函数 onCancel 未声明');
        }
    }
};
</script>
<style>
/* pages/shopmanager/addqualityservice/index.wxss */
.box {
    background: #ffffff;
    box-shadow: 0px 1px 29px 0px rgba(0, 0, 0, 0.04);
    border-radius: 10rpx;
    box-sizing: border-box;
    margin: 20rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    vertical-align: center;
    flex-wrap: nowrap;
    justify-content: center;
    align-content: center;
    padding: 20rpx;
}

.centers {
    width: 100%;
    display: flex;
    flex-direction: row;
    align-items: center;
    vertical-align: center;
    flex-wrap: nowrap;
    justify-content: space-between;
    align-content: center;
    margin: 30rpx;
    font-size: 36rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #333333;
}

.centers_1 {
    width: 75%;
    display: flex;
    flex-direction: row;
    align-items: center;
    vertical-align: center;
    flex-wrap: nowrap;
    justify-content: flex-end;
    align-content: center;
}

.centers_1 text {
    width: 90%;
    text-align: right;
}

/*分割线样式*/
.divLine {
    background: #dadada;
    width: 100%;
    height: 1rpx;
}

.text1 {
    font-size: 32rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
}

.savebtn {
    width: 690rpx;
    height: 90rpx;
    background: #ff8722;
    border-radius: 45rpx;
    font-size: 36rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #f3f3f3;
    line-height: 90rpx;
    text-align: center;
    margin: 30rpx;
    position: relative;
    top: 60rpx;
}

.centers-1 input {
    text-align: right;
    font-size: 28rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
    width: 450rpx;
}

.btn1 {
    width: 400rpx;
    height: 88rpx;
    background: #ff8722;
    border-radius: 22px;
    font-size: 32rx;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #ffffff;
    line-height: 88rpx;
    margin: 0 auto;
    text-align: center;
}

.text2 {
    font-size: 28rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
}
</style>
